<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
          >导入</el-button>
          <el-button
            size="small"
            type="danger"
            @click="exportEmployees"
          >导出</el-button>
          <el-button
            v-if="checkPermission('addEmployee')"
            size="small"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="">
            <template slot-scope="scope">
              <!-- 如果想要得出真正当前页员工的在全部数据的索引
              应该先算出上一页的最后一行
              再次基础上, 当前页再 +1 +2 以此类推 -->
              <!-- 或者可以这么想, 前面所有的总条数基础上 +1 +2 .... -->
              {{ (page.page - 1) * page.size + (scope.$index + 1) }}
            </template>
          </el-table-column>
          <el-table-column label="头像" sortable="" width="200">
            <template slot-scope="{ row }">
              <img
                v-imgerr="require('@/assets/common/head.jpg')"
                class="avatar"
                :src="row.staffPhoto"
                alt=""
                @click="showQRcode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatFormEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template slot-scope="scope">
              <el-switch :value="scope.row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="assginRole(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :total="page.total"
            :current-page="page.page"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <!-- 弹窗组件 -->
      <AddEmployee :show-dialog="showDialog" />
      <!-- 头像预览 -->
      <el-dialog
        title="头像预览"
        :visible="isShowQRcode"
        @close="isShowQRcode = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <AssignRole ref="assignRole" :user-id="userId" :show-role-dialog="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入枚举数据，方便聘用形式的格式化
import employmentEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'

import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import QRCode from 'qrcode'
export default {
  // 局部过滤器的基本用户
  // filters: {
  //   formateTime(valOrigin) {
  //     return valOrigin.split('T')[0]
  //   }
  // },
  components: { AddEmployee, AssignRole },
  data() {
    return {
      list: [],
      page: {
        page: 1, // 页数
        size: 5, // 每页条数
        total: 0 // 总数
      },
      loading: false, // 加载数据
      showDialog: false, // 弹窗
      isShowQRcode: false, // 显示二维码
      showRoleDialog: false, // 分配角色弹窗
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // // 判断当前用户是否有权限 -- 混入对象封装函数替代这段代码
    // checkPermission(pointName) {
    //   // 如果这个权限点名称存在于用户数据的points权限数组中，就可以点击
    //   // 否则不能
    //   return this.$store.getters.roles && this.$store.getters.roles.points.includes(pointName)
    // },
    // 分配角色
    async assginRole(id) {
      await this.$refs.assignRole.getUserDetailById(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 显示二维码
    showQRcode(url) {
      if (url) {
        this.isShowQRcode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.mycanvas, url, {
            width: 300,
            color: {
              dark: '#5081fd'
            }
          })
        })
      }
    },
    // 删除员工
    async delEmployee(id) {
      try {
        // 二次校验
        await this.$confirm('你确认删除吗？')
        // 发请求
        await delEmployee(id)
        // 如果最后一页最后一个删完，页码自动往前跳一页
        if (this.list.length === 1 && this.page.page > 1) {
          this.page.page--
        }
        // 提示
        this.$message.success('删除员工成功')
        // 重新选渲染页面
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 获取员工管理数据列表 -- 封装
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      // console.log(rows, total)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // 分页功能
    currentChange(newPage) {
      // 1、修改翻页配置
      this.page.page = newPage
      // 2、发个请求
      this.getEmployeeList()
    },
    // 数据格式转换
    formatFormEmployment(row, column, cellValue) {
      // 查找格式化的数据
      const obj = employmentEnum.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      // 有找到值就渲染，没有就显示未知
      return obj ? obj.value : '未知'
    },
    // 数据导出
    async exportEmployees() {
      // 这里是按钮点击，可以就在这里单独引入需要的酷
      const { export_json_to_excel } = await import('@/vendor/Export2Excel')
      console.log(export_json_to_excel)
      // 导出时加载所有员工
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.page.total
      })
      console.log(rows)
      // 准备数据转换的字典
      const dict = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const userData = rows.map((user) => {
        return this.object2Array(user, dict)
      })
      console.log(userData)
      export_json_to_excel({
        header: Object.keys(dict),
        data: userData
      })
    },
    object2Array(user, dict) {
      const newUser = []
      for (const key in dict) {
        const enKey = dict[key]
        const value = user[enKey]
        // newUser.push(value)
        // 事件和聘用形式数据的特殊处理
        // 如果是入职时间和转正时间就按照时间格式添加进去新数组
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          newUser.push(new Date(formatDate(value)))
          // 聘用形式的特殊处理
        } else if (enKey === 'formOfEmployment') {
          const obj = employmentEnum.hireType.find((item) => item.id === value)
          newUser.push(obj ? obj.value : '未知')
        } else {
          newUser.push(value)
        }
      }
      return newUser
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 200px;
  height: 200px;
  object-fit: contain;
}
</style>
